let express = require('express');
let router = express.Router();
let {v4}=require('uuid');


//数据存入数据库操作
router.post('/', function(req, res, next) {

  let mes=req.body;
  console.log(req.body)

  var pool = global.POOL;
  var query = async () => {
    var connect = await pool.connect()
    try {
      if(mes.contentid)
      {
        //update
        console.log('update')
        await connect.query(`UPDATE contents SET title=$1::varchar,
        module_name=$2::varchar,content=$3::text,posted=$4::boolean WHERE id=$5::uuid`,
        [mes.title,mes.moduleName,mes.content,mes.posted,mes.contentid]);
        res.send({update:'ok'});
      }
      else{
        //insert
        console.log('insert')
        let id=v4()
        await connect.query(`insert into contents (id,title,module_name,content,posted) values
        ($1::uuid,$2::varchar,$3::varchar,$4::text,$5::boolean)`,[id,mes.title,mes.moduleName,mes.content,mes.posted]);
        res.send({insert:id});
       }
    } finally {
      connect.release()
    }
  }

  query().catch(e => {
    res.send({updateOrInsert:'error'});
    console.error(e.message, e.stack)});
});

module.exports = router;
